package cn.com.swu.mianyangapp.ui.news;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.net.wifi.aware.DiscoverySession;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.android.material.floatingactionbutton.FloatingActionButton;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import cn.com.swu.mianyangapp.R;
import cn.com.swu.mianyangapp.ui.bean.News;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link HomeNewsFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class HomeNewsFragment extends Fragment {
    private String user ="likang";
    private int userid = 1;

    final private String mIp = "192.168.58.15:8081";

    String Tag = "OKHttp_Home_List";
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    private String mParam1;
    private String mParam2;
    private Handler mHandler;
    private List<News> mNews;
    private NewsHomeListAdapter mNewsListAdapter;
    private RecyclerView mRecyclerView;
    private FloatingActionButton mFloatingActionButton;


    public HomeNewsFragment() {
        // Required empty public constructor
    }

    public static HomeNewsFragment newInstance(String param1, String param2) {
        HomeNewsFragment fragment = new HomeNewsFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }
    @SuppressLint("HandlerLeak")
    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initDate();
        mHandler = new Handler(){
            @Override
            public void handleMessage(Message msg) {
                mNews = new ArrayList<>();
                mNews.addAll((List<News>)msg.obj);
                mNewsListAdapter = new NewsHomeListAdapter(getContext(),mNews);
                mRecyclerView = view.findViewById(R.id.news_home_recycler);
                mRecyclerView.getRecycledViewPool();
                mRecyclerView.getRecycledViewPool().setMaxRecycledViews(0, 10);
                mRecyclerView.setAdapter(mNewsListAdapter);
                RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getActivity());
                mRecyclerView.setLayoutManager(layoutManager);



            }
        };
        mFloatingActionButton = view.findViewById(R.id.news_add_float);
        mFloatingActionButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                News news = new News();
                Intent intent = new Intent(v.getContext(), NewsAddActivity.class);
                intent.putExtra("News",news);
                v.getContext().startActivity(intent);
            }
        });
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_home_news, container, false);
    }

    private void initDate() {
        OkHttpClient client = new OkHttpClient();
        FormBody body = new FormBody.Builder().build();
        String url;
        if (mParam1.equals("我的新闻")){
            url = "http://" + mIp + "/select_news/4/" + userid;
        }
        else {
            url = "http://" + mIp + "/query_status_news/" + userid;
        }

        Request request = new Request.Builder()
                .url(url)
                .addHeader("Accept-Language", "zh-CN,zh;q=0.9")
                .post(body)
                .build();
        Log.e(Tag, request.url().toString());
        Call call = client.newCall(request);

        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                String Tag = "OKHttp";
                Log.e(Tag, e.toString());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String result = response.body().string();
                Log.e(Tag, result);
                JSONArray jsonArray = JSON.parseArray(result);
                List<News> list = JSONObject.parseArray(jsonArray.toJSONString(), News.class);
                Message msg = Message.obtain();
                msg.obj = list; // 消息内存存放
                mHandler.sendMessage(msg);
            }
        });
    }
}